﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;

public class ElementManager {
	// === Public =====================================================================================================
	public static ElementManager CreateInstance() {
		var instance = new ElementManager();
		return instance;
	}

	public void CreateElement(FieldElementType type, Vector3 position, GameObject ownerParent = null) {
		CheckCollisionWithOtherElements(position);
		CreateGoElement(type, position, ownerParent);
	}

	public void DestroyElements(List<FieldElement> elements = null) {
		var list = elements ?? new List<FieldElement>(GameData.GetInstance.Elements);
		foreach (var element in list) {
			DestroyElement(element);
		}
	}

	public void DestroyElement(FieldElement element) {
		Object.Destroy(element.GameObject);
		GameData.GetInstance.RemoveElement(element);
	}

	// === Private ====================================================================================================
	private void CheckCollisionWithOtherElements(Vector3 position) {
		if (GameData.GetInstance.Elements.Any(element => position.Equals(element.Position))) {
			throw new Exception("Position " + position + " is occupied");
		}
	}

	private void CreateGoElement(FieldElementType type, Vector3 position, GameObject ownerParent) {
		var prefab = Tools.Prefab.GetPrefab(type);
		var goElement = Tools.Prefab.Create<GameObject>(prefab);
		goElement.transform.position = position;
		if (ownerParent != null) {
			goElement.transform.parent = ownerParent.transform;
		}
		var element = Tools.Element.GetElement(type, goElement);
		GameData.GetInstance.AddElement(element);
	}
}